﻿layui.use(['table', 'form', 'layer', 'jquery', 'laydate', 'tree',], function () {
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.jquery;
    var table = layui.table;
    var laydate = layui.laydate;

    // laydate 初始化
    laydate.render({
        elem: '#datePicker', // 绑定元素
        value: getCurrentDate(), // 设置默认值
        done: function (value, date) { // 监听日期选择完毕
            // 将选择的日期赋值给 #datenow 元素的值
            $('#datePicker').val(value);
            console.log($('#datePicker').val())
            // 重新加载数据
            show();
        }
    });

    //选中单选框启用文本框
    form.on('radio(radior)', function (data) {
        $('input[type="text"][name=residueNum]').prop('disabled', true);

        // 根据选中的单选框启用对应的文本框
        if (data.value === '2') {
            $('[name=residueNum]').prop('disabled', false);
        }
        // 执行layui表单的重新渲染，以更新样式
        layui.form.render();
    });

    $(document).ready(function () {
        // 初始加载数据
        show();
    });

    function mergeSameRows(data) {
        var mergedData = [];
        var prevRow = null;
        data.forEach(function (currentRow) {
            if (prevRow &&
                prevRow.housingPricesId === currentRow.housingPricesId &&
                prevRow.roomId === currentRow.roomId &&
                prevRow.roomName === currentRow.roomName &&
                prevRow.productsName === currentRow.productsName) {
                prevRow.data.push({
                    priceCalendarId: currentRow.priceCalendarId,
                    residueNum: currentRow.residueNum,
                    priceEveryDate: currentRow.priceEveryDate,
                    addTime: currentRow.addTime,
                });
            } else {
                if (prevRow !== null) {
                    mergedData.push(prevRow);
                }
                prevRow = {
                    housingPricesId: currentRow.housingPricesId,
                    roomId: currentRow.roomId,
                    roomName: currentRow.roomName,
                    productsName: currentRow.productsName,
                    otherFields: {
                        canBook: currentRow.canBook,
                        maxCapacity: currentRow.maxCapacity,

                    },
                    data: [{
                        priceCalendarId: currentRow.priceCalendarId,
                        residueNum: currentRow.residueNum,
                        priceEveryDate: currentRow.priceEveryDate,
                        addTime: currentRow.addTime,
                    }]
                };
            }
        });

        // 将最后一行加入到合并后的数据中
        if (prevRow !== null) {
            mergedData.push(prevRow);
        }

        return mergedData;
    }

    function show() {
        // 获取显示值
        var selectedDate = $('#datePicker').val();

        // 发送 POST 请求获取数据
        $.post({
            url: 'http://localhost:5174/api/RoomHousingState/GetRoomMaintenanceList',
            contentType: "application/json",
            data: JSON.stringify({ date: selectedDate }),
            headers: {
                "Authorization": "Bearer " + localStorage.getItem('token')
            },
            async: true,
            success: function (res) {
                console.log(res.data)
                var mergedData = mergeSameRows(res.data);

                // 获取接下来10天的日期及星期几
                var dates = [];
                for (var i = 0; i < 10; i++) {
                    var tempDate = new Date(selectedDate);
                    tempDate.setDate(tempDate.getDate() + i);
                    var formattedDate = formatDate(tempDate) + ' ' + getWeekday(tempDate);
                    dates.push(formattedDate);
                }

                // 生成表格列的定义
                var tableCols = [
                    { field: 'roomName', title: '房型', width: 150 },
                    { field: 'productsName', title: '产品名称', width: 150 }
                ];

                var numbersInEnglish = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

                // 动态添加日期相关列
                dates.forEach(function (date, index) {
                    console.log(date)
                    console.log(index)
                    var column = {
                        title: date,
                        width: 150,
                        event: numbersInEnglish[index],
                        templet: function (d) {
                            console.log(d)
                            var dataIndex = index;
                            var dataForDate = d.data[dataIndex];
                            if (dataForDate) {
                                // 返回当前日期的数据
                                return '余' + dataForDate.residueNum + '间/售' + 0 + '间<br>￥' + dataForDate.priceEveryDate +
                                    `<input type="text" style="display:none" value="${dataForDate.addTime}">`;
                            } else {
                                return '';
                            }
                        }
                    };
                    tableCols.push(column);
                });

                // 渲染表格数据
                layui.use('table', function () {
                    var table = layui.table;
                    table.render({
                        elem: '#demoTable',
                        data: mergedData,
                        cols: [tableCols]
                    });
                });
            },
            error: function (error) {
                console.error(error);
            }
        });
    }


    table.on('tool(demoTable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'one':
            case 'two':
            case 'three':
            case 'four':
            case 'five':
            case 'six':
            case 'seven':
            case 'eight':
            case 'nine':
            case 'ten':
                popup(obj.event, data); // 传递事件类型和数据给弹出窗口处理函数
                break;
        }

        function popup(eventType, data) {
            // 获取外部定义的弹出层内容
            var HousingState = document.getElementById('HousingState').innerHTML;

            // 弹出页面层
            layer.open({
                type: 1,
                title: '调整房态/房量',
                area: ['700px', '400px'], // 宽高
                content: HousingState,
                success: function (layero, index) {
                    $("[name=productsName]").html(data.productsName); // 使用传入的数据
                    switch (eventType) {
                        case 'one':
                            $("[name=effectivedate]").html((data.data[0].addTime).substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[0].priceCalendarId));
                            break;
                        case 'two':
                            $("[name=effectivedate]").html(data.data[1].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[1].priceCalendarId));
                            break;
                        case 'three':
                            $("[name=effectivedate]").html(data.data[2].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[2].priceCalendarId));
                            break;
                        case 'four':
                            $("[name=effectivedate]").html(data.data[3].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[3].priceCalendarId));
                            break;
                        case 'five':
                            $("[name=effectivedate]").html(data.data[4].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[4].priceCalendarId));
                            break;
                        case 'six':
                            $("[name=effectivedate]").html(data.data[5].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[5].priceCalendarId));
                            break;
                        case 'seven':
                            $("[name=effectivedate]").html(data.data[6].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[6].priceCalendarId));
                            break;
                        case 'eight':
                            $("[name=effectivedate]").html(data.data[7].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").hvaltml((data.data[7].priceCalendarId));
                            break;
                        case 'nine':
                            $("[name=effectivedate]").html(data.data[8].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[8].priceCalendarId));
                            break;
                        case 'ten':
                            $("[name=effectivedate]").html(data.data[9].addTime.substring(0, 10));
                            $("[name=priceCalendarId]").val((data.data[9].priceCalendarId));
                            break;
                        default:
                            $("[name=effectivedate]").html(''); // 其他情况的处理
                            $("[name=priceCalendarId]").val(''); // 其他情况的处理
                            break;
                    }

                    form.render();

                    // 表单提交监听
                    form.on('submit(affirm)', function (formData) {
                        //阻止重复提交
                        formData.elem.disabled = true;

                        console.log(formData.field)
                        if (formData.field.State == "1") {
                            formData.field.residueNum = -1;
                        }
                        console.log(formData.field)
                        $.ajax({
                            url: 'http://localhost:5174/api/RoomHousingState/UpdatePriceCalendar',
                            type: 'post',
                            contentType: "application/json",
                            data: JSON.stringify(formData.field),
                            success: function (res) {
                                // 添加成功后的操作
                                if (res.code > 0) {
                                    layer.msg("修改成功");
                                    show()
                                }
                            },
                            error: function (error) {
                                console.error(error);
                            }
                        });
                        layer.closeAll(); // 关闭所有弹出层
                        return false; // 阻止表单的默认提交
                    });
                }
            });
        }

    });


    // 弹出层取消按钮
    $(document).on('click', '[lay-on="closeFormBtn"]', function () {
        layer.closeAll(); // 关闭所有弹出层
    });

    // 辅助函数：格式化日期为 MM/DD
    function formatDate(date) {
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        return month + '/' + day;
    }

    // 辅助函数：获取日期对应的星期几
    function getWeekday(date) {
        var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return weekdays[date.getDay()];
    }

    // 获取当前日期并格式化为 yyyy-mm-dd
    function getCurrentDate() {
        const today = new Date();
        const yyyy = today.getFullYear();
        const mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
        const dd = String(today.getDate()).padStart(2, '0');
        return yyyy + '-' + mm + '-' + dd;
    }
});